<template>
  <div class="login">
    <el-row style="margin-top: 260px;z-index: 1;" width="40%">
      <el-col :model="user" :offset="9" :span="6">
        <el-card class="login-box" v-loading="$store.state.loading" element-loading-background="rgba(0, 0, 0, 0.8)">
          <el-form :model="user" :rules="rules" ref="user">
            <h1 class="title">欢迎使用LDU在线考试系统</h1>
            <!-- <p class="login-box-msg">疾如风，徐如林!</p> -->
            <el-form-item prop="userName">
              <el-input type="text" v-model="user.userName" auto-complete="off" placeholder="请输入用户名..." suffix-icon="el-icon-bell"></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input type="password" v-model="user.password" auto-complete="off" placeholder="请输入密码..." suffix-icon="el-icon-edit"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="login('user')" :loading="$store.state.loading" class="pull-right" style="width:100%">登录</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="dialogFormVisible = true" :loading="$store.state.loading" class="pull-right" style="width:100%">注册</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  <el-dialog title="用户注册" :visible.sync="dialogFormVisible" width="35%" center >
  <el-form ref="ruleForm2" :model="ruleForm2" label-width="100px" class="demo-ruleForm" :rules="rules2">
  <el-form-item label="用户名:" prop="name">
    <el-input v-model="ruleForm2.name"></el-input>
  </el-form-item>
  <el-form-item label="密码:" prop="password">
    <el-input  type="password" v-model="ruleForm2.password" autocomplete="off"></el-input>
  </el-form-item>
  <el-form-item label="确认密码:" prop="checkPass">
    <el-input type="password" v-model="ruleForm2.checkPass" autocomplete="off"></el-input>
  </el-form-item>
  <el-form-item label="角色">
          <el-select v-model="ruleForm2.roles.id" placeholder="请选择" clearable>
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
  </el-form-item>
  <!-- <el-form-item id="class" label="所在班级" style="display:none">
          <el-select v-model="ruleForm2.cla.id" placeholder="请选择" clearable>
            <el-option
              v-for="item in options1"
              :key="item.id"
              :label="item.claName"
              :value="item.id">
            </el-option>
          </el-select>
  </el-form-item> -->
  <!-- <el-form-item id="class1" label="分管班级" style="display:none">
          <el-select v-model="ruleForm2.cla.id" placeholder="请选择" clearable>
            <el-option
              v-for="item in options1"
              :key="item.id"
              :label="item.claName"
              :value="item.id">
            </el-option>
          </el-select>
  </el-form-item> -->
</el-form>
  <div slot="footer" class="dialog-footer">
    <el-button type="primary" @click="onSubmit('ruleForm2')">提交</el-button>
    <el-button @click="dialogFormVisible = false">取 消</el-button>
  </div>
</el-dialog>
  </div>
</template>
<style>
.login {
  background: url(../assets/bg.png) no-repeat scroll center center / cover;
  background-size: 100% 100%;
  width: 100%;
  height: 100%;
  position: fixed;
}

.login-box {
  background: #ffffff;
  border: none;
}

.login-box-msg {
  color: #000000;
  text-align: center;
}

.login-box .title {
  color: #000000;
  text-align: center;
}
</style>
<script>
import axios from 'axios';
export default {
  name: "Login",
  data() {
    var validatePass = (rule, value, callback) => {
        if (value == ''|| typeof(value) == "undefined") {
          callback(new Error('请输入密码'));
        } else {
          if (this.ruleForm2.checkPass !== '') {
            this.$refs.ruleForm2.validateField('checkPass');
          }
          callback();
        }
      };
      var validatePass2 = (rule, value, callback) => {
        if (value == '' || typeof(value) == "undefined") {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.ruleForm2.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      var validateName = (rule,value,callback) => {
        if(typeof(value) == "undefined" || value == ""){
          callback(new Error('请输入用户名'));
        }else{
            this.$http.get("/api/accounts/",{params:{'name':this.ruleForm2.name}}).then(res => {
          if(res.data.content.length == 0){
            callback();
          }else{
            callback(new Error('该用户名已被注册'));
          }
        })
        }
      };
    return {
      options1: new Array(),
      options: new Array(),
      user: {
        userName: "root",
        password: "1"
      },
      ruleForm2: {
          name: '',
          password: '',
          checkPass: '',
          state: '',
          roles:[{
            id:'',
          }],
          
        },
      rules: {
        userName:[
          { required:true, message: '请输入用户名', trigger: 'change'}
        ],
        password:[
          { required:true, message: '请输入密码', trigger: 'change'}
        ]
      },
      rules2:{name:[{required:true,validator:validateName,trigger:'blur'}],
          password:[{required:true,validator:validatePass, trigger: 'blur'}],
          checkPass:[{required:true,validator:validatePass2, trigger: 'blur'}]
      },
      dialogTableVisible: false,
      dialogFormVisible: false,
    };
  },
  mounted() {
    this.getDropList();
  },
  methods: {
    login(userForm) {
      this.$refs[userForm].validate((valid) => {
        if (valid) {
            this.$http.get("/api/accounts/authentication",{params:{'username':this.user.userName,'password':this.user.password}}).then(res => {
            if (res.data.token) {
              this.$store.commit("setToken", res.data.token);
              this.$store.commit("setUserNickName", res.data.user.nickname);
              this.$store.commit("setUserId", res.data.user.id);
              this.$store.commit("setPic", 'data:image/png;base64,'+res.data.user.pic);

              console.info(res.data.user);
              if(res.data.user.studentCla && res.data.user.studentCla.exam)
              {
                this.$store.commit("setExamTime",res.data.user.studentCla.exam.examTime);
                this.$store.commit("setExamName",res.data.user.studentCla.exam.name);
              }
              if(res.data.user.isExamed)
              {
                this.$store.commit("setIsfinishedExam", res.data.user.isExamed);
              }
              if(res.data.user.roles && res.data.user.roles[0])
              {
                this.$store.commit("setRole", res.data.user.roles[0].name);
              }else{
                this.$store.commit("setRole", '管理员');
              }
              if(res.data.noticeNum)
              {
                this.$store.commit("setNoticeNum", res.data.noticeNum);
              }
              this.$router.push({ path: "/system/notice" });
        }else{
          this.$notify({type:'error',title:'登录失败',message:'未知错误'}) ;
        }
      });
          } else {
            return false;
          }
      })
      
    }
    ,
    onSubmit(ruleForm2) {

        this.$refs[ruleForm2].validate((valid) => {
          if(valid){
            this.ruleForm2.state = 'true';
            console.info(this.ruleForm2);
            // this.ruleForm2.
            this.$http.post("/api/accounts/?roleId="+this.ruleForm2.roles.id,this.ruleForm2).then(res => {
              if(res.status == 200 && res.data != ''){
                this.$notify({type:'success',title:'注册成功',message:'恭喜你,注册成功!'}) ;
                this.dialogFormVisible = false;
                this.ruleForm2 ={name: '',password: '',checkPass: '',state: '',roles:[{id:''}]};
              }else{
                this.$notify({type:'error',title:'提示',message:'注册失败!'}) ;
              }
            })
          }
        })
      }
      ,
    getDropList(){
      this.$http.get("/api/roles/noPage").then(res => {
        this.options = res.data;
      })
      // this.$http.get("/api/cla/noPage").then(res => {
      //   this.options1 = res.data;
      // })
    },
    // selectTrigger(val) {
    //     if(val)
    //     {
    //       this.$http.get("/api/roles/confirmRole",{params:{'roleId':val}}).then(res => {
    //         var cla = document.getElementById('class');//所在班级
    //         var cla1 = document.getElementById('class1');//分管班级
    //         if(res.data == 'student')
    //         {
    //           cla.style.display = "block";
    //           cla1.style.display = "none";
    //         }else if (res.data == 'teacher')
    //         {
    //           cla.style.display = "none";
    //           cla1.style.display = "block";
    //         }else{
    //           cla.style.display = "none";
    //           cla1.style.display = "none";
    //         }
    //       })
    //     }
    // }
  }
};
</script>
<style scope>
.el-dialog__wrapper{
  z-index: 9999;
}
</style>
